package api;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        // 1. 从请求中获取到用户名和密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        if (username == null || password == null){
            String html = "<h3>登陆失败！</h3>";
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write(html);
            return;
        }

        UserDao userDao = new UserDao();
        User user = userDao.selectUserByName(username);
        if (user == null){
            String html = "<h3>用户名或密码错误！</h3>";
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write(html);
            return;
        }
        if (!user.getPassword().equals(password)){
            String html = "<h3>登陆失败！</h3>";
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write(html);
            return;
        }
        // 登录界面是需要设置会话的,会话类似于哈希表用来存储键值对
        HttpSession  session = req.getSession(true);
        session.setAttribute("user", user);
        // 返回一个重定向响应
        resp.sendRedirect("blog_list.html");
    }

    // 通过这个方法，判定用户的登录状态
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 通过会话
        HttpSession session = req.getSession(false);
        if (session == null){
            resp.setStatus(403);
            return;
        }
        User user = (User) session.getAttribute("user");
        if (user == null){
            resp.setStatus(403);
            return;
        }

        resp.setStatus(200);
        resp.setContentType("application/json;charset=utf8");
        String respJson = objectMapper.writeValueAsString(user);
        resp.getWriter().write(respJson);
    }
}




